package in.abip.chisame;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetSocketAddress;
import java.net.Socket;

public class TcpTelnetClient implements ITelnetClient {
	private Socket _socket = null;
	private BufferedReader _bufferedReader = null;
	private BufferedWriter _bufferedWriter = null;
	
	public Boolean connect(String host, int port) {
		try {
			InetSocketAddress address = new InetSocketAddress(host, port);
			_socket = new Socket();
			_socket.connect(address, 100);
			_bufferedWriter = new BufferedWriter(new OutputStreamWriter(
					_socket.getOutputStream()), 1024);
			_bufferedReader = new BufferedReader(new InputStreamReader(
					_socket.getInputStream()), 1024);
//			_socket.setKeepAlive(true);
			_socket.setSoTimeout(100);
			int rst = 0;
			while (rst != 1) {
				try {
					rst = _bufferedReader.read();
				} catch (IOException e) {
					rst = 1;
				}
			}
		} catch (IOException e) {
			return false;
		}
		return true;
	}

	public void disconnect() {
		try {
			_socket.close();
		} catch (IOException e) {}
	}

	public String attention(String command) {
		String result;
		try {
			_bufferedWriter.write(command + "\n", 0, command.length() + 1);
			_bufferedWriter.flush();
		} catch (IOException e) {
			return null;
		}
		try {
			result = _bufferedReader.readLine();
			return result;
		} catch (IOException e) {
			return null;
		}
	}

}
